/*
 * Copyright (c) 2010, Baturu.COM. All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * under the License.
 */
package com.baturu.oss;

import org.sitevelocity.exceptions.NotMatchedException;
import org.sitevelocity.utils.SiteVelocityUtil;
import org.sitevelocity.web.utils.URLRewriter;

/**
 * default url rewriter.
 *
 * @author javafuns
 */
public class DefaultURLRewriter implements URLRewriter {

    @Override
    public String translate(String fromPattern, String toPattern, String fromURL)
            throws NotMatchedException {
        if (SiteVelocityUtil.isBlank(toPattern)) {
            return fromURL;
        }
        if (SiteVelocityUtil.isBlank(fromPattern) || SiteVelocityUtil.isBlank(fromURL)) {
            throw new NotMatchedException("from pattern : " + fromPattern + ", to pattern : " + toPattern
                    + ", from URL : " + fromURL);
        }

        String[] fs = fromPattern.split("/");
        String[] fus = fromURL.split("/");
        //TODO: need to complete
        if (fs.length != fus.length) {
            throw new NotMatchedException("from pattern : " + fromPattern + ", to pattern : " + toPattern
                    + ", from URL : " + fromURL);
        }
        String toURL = toPattern;
        for (int i = 0; i < fs.length; i++) {
            if (fs[i].equals(fus[i])) {
                continue;
            }
            toURL = toURL.replaceAll(fs[i], fus[i]);
        }
        return toURL;
    }

    @Override
    public boolean isMatched(String pattern, String url) {
        if (SiteVelocityUtil.isBlank(pattern) || SiteVelocityUtil.isBlank(url)) {
            throw new NullPointerException("Empty strings to be matched.");
        }
        String[] fs = pattern.split("/");
        String[] fus = url.split("/");
        // TODO:
        if (fs.length != fus.length) {
            return false;
        }
        for (int i = 0; i < fs.length; i++) {
            if (fs[i].equals(fus[i])) {
                continue;
            }
            if (!fs[i].startsWith("@") || !fs[i].endsWith("@")) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) throws NotMatchedException {
        DefaultURLRewriter r = new DefaultURLRewriter();
        System.out.println(r.translate("/admin/post/@postid@/edit.vm", "/admin/post/edit.vm?entry=@postid@", "/admin/post/1/edit.vm"));
    }
}
